package StringSecond.SwordOffer.StringSecond;

public class LongestPalindrome {
    /**
     * 最长回文子串
     * 给你一个字符串 s，找到 s 中最长的回文子串。
     * <p>
     * 示例 1：
     * <p>
     * 输入：s = "babad"
     * 输出："bab"
     * 解释："aba" 同样是符合题意的答案。
     * 示例 2：
     * <p>
     * 输入：s = "cbbd"
     * 输出："bb"
     */
    public static String longestPalindrome(String s) {
        int length = s.length();
        if (s.length() == 1) {
            return s;
        }
        boolean[][] isPalindrome = new boolean[length][length];
        for (int i = 0; i < length; i++) {
            isPalindrome[i][i] = true;
        }
        int max = 1;
        int begin = 0;
        char[] chars = s.toCharArray();
        for (int len = 2; len <= length; len++) {
            for (int i = 0; i < length; i++) {
                int j = i + len - 1;
                if (j >= length) {
                    break;
                }
                if (chars[i] != chars[j]) {
                    isPalindrome[i][j] = false;
                } else {
                    if (j - i == 2) {
                        isPalindrome[i][j] = true;
                    } else {
                        isPalindrome[i][j] = isPalindrome[i + 1][j - 1];
                    }
                }
                if (isPalindrome[i][j] && len > max) {
                    begin = i;
                    max = len;
                }
            }
        }
        return s.substring(begin, begin + max);
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad"));
    }
}
